<template>
  <div>
    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="success" @click="handleAddPost">发布帖子</el-button>
    </div>

    <!-- 帖子表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="postId" label="帖子ID" width="80"/>
      <el-table-column prop="title" label="标题" show-overflow-tooltip/>
      <el-table-column prop="createdTime" label="发布时间" width="180"/>
      <el-table-column prop="updatedTime" label="更新时间" width="180"/>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditPost(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeletePost(scope.row.postId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑帖子对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="90%">
      <div class="dialog-content">
        <!-- 左侧帖子编辑 -->
        <div class="post-edit">
          <el-form :model="currentForm" :rules="rules" ref="postFormRef">
            <el-form-item label="标题" prop="title">
              <el-input v-model="currentForm.title" placeholder="请输入标题"/>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <WangEditorView v-model="currentForm.content" :key="refreshKey"/>
            </el-form-item>
          </el-form>
        </div>
        <!-- 右侧评论列表 -->
        <div class="comment-list" v-if="dialogTitle === '编辑帖子'">
          <div class="comment-header">
            <h3>评论列表</h3>
            <el-button type="primary" size="small" @click="fetchComments">刷新</el-button>
          </div>
          <el-table :data="commentList" border style="width: 100%;">
            <el-table-column prop="content" label="评论内容" show-overflow-tooltip/>
            <el-table-column prop="createTime" label="评论时间" width="180"/>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button type="danger" size="small" @click="handleDeleteComment(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {
  postCommentDeleteOne,
  postCommentSelectList,
  postDeleteOne,
  postInsertOne,
  postSelectPage,
  postUpdateOne
} from "@/api/post.js";
import WangEditorView from '@/components/WangEditorView.vue';
import {getUser} from "@/utils/auth.js";

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const refreshKey = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const currentForm = reactive({
  postId: null,
  userId: null,
  title: '',
  content: '',
  createdTime: '',
  updatedTime: '',
});
const postFormRef = ref(null);

// 验证规则
const rules = {
  title: [
    {required: true, message: '标题不能为空', trigger: 'blur'},
    {min: 2, max: 50, message: '标题长度在2到50个字符之间', trigger: 'blur'}
  ],
  content: [
    {required: true, message: '内容不能为空', trigger: 'blur'},
    {min: 10, message: '内容长度不能少于10个字符', trigger: 'blur'}
  ],
};

// 评论列表数据
const commentList = ref([]);

// 获取帖子列表
const fetchPosts = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    };
    if (!params.title) {
      delete params.title;
    }
    if (!params.content) {
      delete params.content;
    }
    const response = await postSelectPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取帖子列表失败');
  }
};

// 新增帖子
const handleAddPost = () => {
  refreshKey.value++;
  dialogTitle.value = '发布帖子';
  dialogVisible.value = true;
  resetForm();
};

// 编辑帖子
const handleEditPost = (row) => {
  refreshKey.value++;
  dialogTitle.value = '编辑帖子';
  dialogVisible.value = true;
  Object.assign(currentForm, row);
  // 获取评论列表
  fetchComments();
};

// 删除帖子
const handleDeletePost = (postId) => {
  ElMessageBox.confirm('确认删除该帖子?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await postDeleteOne(postId);
      ElMessage.success('删除成功');
      await fetchPosts();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 保存帖子（新增/编辑）
const handleSubmit = () => {
  postFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentForm.postId) {
          // 编辑
          await postUpdateOne(currentForm);
        } else {
          // 新增
          currentForm.userId = getUser().userId;
          await postInsertOne(currentForm)
        }
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        await fetchPosts();
      } catch (error) {
        ElMessage.error('保存失败');
      } finally {
        resetForm();
      }
    }
  });
};

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchPosts();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchPosts();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchPosts();
};

// 重置搜索
const resetSearch = () => {
  currentPage.value = 1;
  Object.assign(searchForm, {
    title: '',
    content: '',
  });
  fetchPosts();
};

// 重置表单
const resetForm = () => {
  Object.assign(currentForm, {
    postId: null,
    userId: null,
    title: '',
    content: '',
    createdTime: '',
    updatedTime: '',
  });
  postFormRef.value?.clearValidate();
};

// 获取评论列表
const fetchComments = async () => {
  try {
    const response = await postCommentSelectList({
      postId: currentForm.postId,
    });
    commentList.value = response.data;
  } catch (error) {
    ElMessage.error('获取评论列表失败');
  }
};

// 删除评论
const handleDeleteComment = (commentId) => {
  ElMessageBox.confirm('确认删除该评论?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await postCommentDeleteOne(commentId);
      ElMessage.success('删除成功');
      await fetchComments();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 初始化数据
onMounted(() => {
  fetchPosts();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.w-e-text-container) {
  min-height: 400px !important;
}

.dialog-content {
  display: flex;
  gap: 20px;
}

.post-edit {
  flex: 1;
}

.comment-list {
  width: 500px;
  border-left: 1px solid #dcdfe6;
  padding-left: 20px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.comment-header h3 {
  margin: 0;
}
</style>
